package com.example.fruitdb.controller;

import com.example.fruitdb.entity.Fruit;
import com.example.fruitdb.service.FruitService;
import com.example.fruitdb.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Vector;

@WebServlet("/queryFruit")
public class FruitServlet extends HttpServlet {
    private FruitService fruitService = new FruitService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        Vector<Fruit> v = fruitService.getAll();
        request.getSession().setAttribute("fruits", v);

        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String fruitName = request.getParameter("fruitName");
        System.out.println(fruitName);
        if(StringUtil.isEmpty(fruitName)) doGet(request,response);
        else {
            Vector<Fruit> v = fruitService.getFruitByName(fruitName.trim());

            request.getSession().setAttribute("fruits", v);
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }

    }
}
